package com.juyu.miliao.api.dao.redis;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.juyu.miliao.api.cache.RedisKeyPrefix;
import com.juyu.miliao.api.dao.mysql.WinRecordFruitMachineInfoDao;
import com.juyu.miliao.api.domain.WinRecordFruitMachineInfo;
import com.juyu.miliao.common.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * @author xuanqicheng
 * @create 2019-16-10:46
 */
@Repository
public class WinRecordFruitMachineInfoRedisDao {

    private String WIN_RECORD_FRUIT_MACHINE_INFO = RedisKeyPrefix.MI_LIAO_API_KEY+"winRecordFruitMachineList";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    private WinRecordFruitMachineInfoDao winRecordFruitMachineInfoDao;

    public void addInfo(WinRecordFruitMachineInfo winRecordFruitMachineInfo){

        winRecordFruitMachineInfoDao.addWinRecordFruitMachineInfo(winRecordFruitMachineInfo);

        String message = JSONObject.toJSONString(winRecordFruitMachineInfo);

        int score = winRecordFruitMachineInfo.getId();

        stringRedisTemplate.opsForZSet().add(WIN_RECORD_FRUIT_MACHINE_INFO,message,score);

        stringRedisTemplate.expire(WIN_RECORD_FRUIT_MACHINE_INFO,30,TimeUnit.MINUTES);
    }

    public List<String> getWinRecordList(int size){

        Set<String> set=stringRedisTemplate.opsForZSet().reverseRange(WIN_RECORD_FRUIT_MACHINE_INFO,0,size);

        if(set.size()>0){
            return new ArrayList<>(set);
        }else{
            setWinRecordFruitMachineBySize(size);
            Set<String> stringSet=stringRedisTemplate.opsForZSet().reverseRange(WIN_RECORD_FRUIT_MACHINE_INFO,0,size);
            if(stringSet.size()>0){
                return new ArrayList<>(stringSet);
            }else{
                return new ArrayList<>();
            }

        }
    }

    private synchronized void setWinRecordFruitMachineBySize(int size) {
        List<WinRecordFruitMachineInfo> list=winRecordFruitMachineInfoDao.selectListByWinInfoSize(100);
        for(WinRecordFruitMachineInfo obj : list){
            String message = JSONObject.toJSONString(obj);
            int score = obj.getId();
            stringRedisTemplate.opsForZSet().add(WIN_RECORD_FRUIT_MACHINE_INFO,message,score);
        }

        stringRedisTemplate.expire(WIN_RECORD_FRUIT_MACHINE_INFO,30,TimeUnit.MINUTES);
    }


}
